package com.xunqi.mall.interceptor;

import com.xunqi.mall.consts.MallConst;
import com.xunqi.mall.exception.UserLoginException;
import com.xunqi.mall.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @Created with IntelliJ IDEA.
 * @author: 夏沫止水
 * @create: 2020-04-23 18:55
 **/
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("preHandle...");

        //从session中获取用户的信息
        UserLoginVo user = (UserLoginVo) request.getSession().getAttribute(MallConst.CURRENT_USER);

        //判断session中是否存在该用户的信息，若不存在则返回给前端（用户未登录，请先登录)提示信息
        if (user == null) {
            log.info("user=null");
            throw new UserLoginException();
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
